package com.hb.trade.api.routine.sms.service;

import cfca.org.slf4j.Logger;
import cfca.org.slf4j.LoggerFactory;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hb.core.pojo.center.au.dto.*;
import com.hb.core.pojo.center.au.entity.User;
import com.hb.core.pojo.enums.NoticeNatureEnum;
import com.hb.core.pojo.enums.RoleSignEnum;
import com.hb.core.pojo.enums.SmsTypeEnum;
import com.hb.core.pojo.project.calibration.dto.BidWinResultDTO;
import com.hb.core.pojo.project.deal.dto.BidCandidateDTO;
import com.hb.core.pojo.project.file.entity.BidBuyRecord;
import com.hb.core.pojo.project.notice.dto.TenderInviteEnterpriseDTO;
import com.hb.core.pojo.project.notice.entity.Notice;
import com.hb.core.pojo.project.notice.entity.TenderInviteEnterprise;
import com.hb.core.pojo.project.order.dto.UserOrderDTO;
import com.hb.core.pojo.project.proj.entity.AbstractProject;
import com.hb.core.pojo.project.section.dto.*;
import com.hb.core.pojo.project.section.entity.BidDownRecord;
import com.hb.core.pojo.project.section.entity.BidSection;
import com.hb.core.pojo.project.section.entity.Problem;
import com.hb.core.pojo.project.section.entity.SupplyBidSignup;
import com.hb.core.pojo.project.sms.dto.SmsSendLogDTO;
import com.hb.trade.client.center.OrgClient;
import com.hb.trade.client.center.UserClient;
import com.hb.trade.client.project.*;
import org.fzzn.core.model.enums.LogicEnum;
import org.fzzn.core.model.msg.Message;
import org.fzzn.core.third.sms.service.SmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author yuezheng
 */
@Service
public class SmsSendService {

    @Autowired
    private OrgClient orgClient;
    @Autowired
    private SmsService smsService;
    @Autowired
    private UserClient userClient;
    @Autowired
    private ClarifyClient clarifyClient;
    @Autowired
    private SectionClient sectionClient;
    @Autowired
    private ProjectClient projectClient;
    @Autowired
    private SmsSendLogClient smsSendLogClient;
    @Autowired
    private BidOpeningClient bidOpeningClient;
    @Autowired
    private BidFileInfoClient bidFileInfoClient;
    @Autowired
    private TenderInviteEnterpriseClient tenderInviteEnterpriseClient;
    @Resource
    private DealClient dealClient;
    @Resource
    private BidWinResultClient bidWinResultClient;

    private static Logger logger = LoggerFactory.getLogger(SmsSendService.class);

    /**
     * 投标人注册短信提醒
     *
     * @param zappUserDTO
     * @param code
     * @return void
     * @author yuezheng
     * @date 2022/4/17 10:23 PM
     */
    @Async("taskExecutor")
    public void tenderRegister(ZappUserDTO zappUserDTO, String code) {
        User user = userClient.getByUsername(zappUserDTO.getUserName()).getData();
        if (user.getUserStatus().equals(1)) {
            // 短信通知
            boolean sendSms = smsService.sendSms(zappUserDTO.getTelephoneNum(), code, null);
            // 短信日志记录
            SmsSendLogDTO smsSendLogDTO = new SmsSendLogDTO();
            smsSendLogDTO.setSendName(zappUserDTO.getPersonName());
            smsSendLogDTO.setSendPhone(zappUserDTO.getTelephoneNum());
            smsSendLogDTO.setSendModul(SmsTypeEnum.REGISTER.getShowName());
            smsSendLogDTO.setSendTemplate(SmsTypeEnum.REGISTER.getTemplate());
            smsSendLogDTO.setSendStatus(sendSms ? 1 : 2);
            smsSendLogDTO.setCreateTime(LocalDateTime.now());
            smsSendLogClient.save(smsSendLogDTO);
        }
    }

    /**
     * 招标人注册短信提醒
     *
     * @param agencyUserDTO
     * @param code
     * @return void
     * @author yuezheng
     * @date 2022/4/18 8:36 AM
     */
    @Async("taskExecutor")
    public void register(AgencyUserBidDTO agencyUserDTO, String code) {
        // 获取用户电话号码
        User user = userClient.getByUserId(agencyUserDTO.getId()).getData();

        String phone = user.getPhone();
        boolean sendSms = smsService.sendSms(phone, code, null);
        // 发送日志
        SmsSendLogDTO smsSendLogDTO = new SmsSendLogDTO();
        smsSendLogDTO.setSendName(user.getUsername());
        smsSendLogDTO.setSendPhone(phone);
        smsSendLogDTO.setSendModul(SmsTypeEnum.TENDERREGISTER.getShowName());
        smsSendLogDTO.setSendTemplate(SmsTypeEnum.TENDERREGISTER.getTemplate());
        smsSendLogDTO.setSendStatus(sendSms ? 1 : 2);
        smsSendLogDTO.setCreateTime(LocalDateTime.now());
        smsSendLogClient.save(smsSendLogDTO);
    }


    /**
     * 邀请书编辑短信提醒
     *
     * @param noticeDTO
     * @param code
     * @return void
     * @author yuezheng
     * @date 2022/4/18 11:17 AM
     */
    @Async("taskExecutor")
    public void release(Notice noticeDTO, String code) {
        List<User> sendUserList = new ArrayList<>();
        // 查询公告所在项目是否为邀请
        AbstractProject projectQueryParam = new AbstractProject();
        projectQueryParam.setId(noticeDTO.getProjectId());
        Message<AbstractProject> abstractProjectMessage = projectClient.projectDetail(projectQueryParam);
        if (abstractProjectMessage.getData().getCommonType().equals(2)) {
            // 查询邀请书中邀请的投标人
            TenderInviteEnterpriseDTO tenderInviteEnterpriseDTO = new TenderInviteEnterpriseDTO();
            tenderInviteEnterpriseDTO.setNoticeId(noticeDTO.getId());
            List<TenderInviteEnterprise> inviteEnterpriseList = tenderInviteEnterpriseClient.findInviteEnterpriseListByNoticeId(tenderInviteEnterpriseDTO).getData();
            Set<String> orgSet = inviteEnterpriseList.stream().map(TenderInviteEnterprise::getOrgId).collect(Collectors.toSet());
            if (CollUtil.isEmpty(inviteEnterpriseList)) {
                logger.info("邀请企业为空");
                return;
            }
            // 查询邀请人联系方式
            for (String item : orgSet) {
                OrgDTO org = orgClient.getOrgById(Long.valueOf(item)).getData();
                UserDTO queryParam = new UserDTO();
                queryParam.setOrgId(org.getId());
                queryParam.setRoleSign(RoleSignEnum.BIDDER.getCode());
                // 获取企业下面的管理员
                Message<User> managerByOrgId = userClient.findManagerByOrgId(queryParam);
                if (managerByOrgId.isSuccess() && null != managerByOrgId.getData()) {
                    sendUserList.add(managerByOrgId.getData());
                }
            }
            if (CollUtil.isEmpty(sendUserList)) {
                logger.info("发送短信用户列表为空");
                return;
            }
            Set<String> phoneSet = sendUserList.stream().map(User::getPhone).collect(Collectors.toSet());
            // 发送短信
            for (String phone : phoneSet) {
                JSONObject pushData = JSONUtil.createObj().putOpt("name", abstractProjectMessage.getData().getProjectName());
                boolean sendSms = smsService.sendSms(phone, code, pushData);
                // 发送日志
                SmsSendLogDTO smsSendLogDTO = new SmsSendLogDTO();
                smsSendLogDTO.setSendPhone(phone);
                smsSendLogDTO.setSendModul(SmsTypeEnum.INVITATION.getShowName());
                smsSendLogDTO.setSendTemplate(SmsTypeEnum.INVITATION.getTemplate());
                smsSendLogDTO.setSendStatus(sendSms ? 1 : 2);
                smsSendLogDTO.setCreateTime(LocalDateTime.now());
                smsSendLogClient.save(smsSendLogDTO);
            }
        }
    }


    /**
     * 公告编辑短信提醒
     *
     * @param notice
     * @return void
     * @author yuezheng
     * @date 2022/4/18 8:36 AM
     */
    @Async("taskExecutor")
    public void noticeRelease(Notice notice, String code) {
        List<User> userList = new ArrayList<>();
        HashSet<Long> userId = new HashSet<>();
        HashMap<String, User> userMap = new HashMap<>();

        if (notice.getNoticeNature() == NoticeNatureEnum.FIRST.getCode()) {
            logger.info("公告发布为首次公告");
            return;
        }
        Message<List<BidSectionDTO>> sectionMessage = sectionClient.findBidSectionsByNoticeId(notice.getId());
        List<BidSectionDTO> sectionList = sectionMessage.getData();
        if (CollUtil.isEmpty(sectionList)) {
            logger.info("公告关联标段为空");
            return;
        }
        // 获取公告所属项目信息
        AbstractProject abstractProject = projectClient.detailBySectionId(sectionList.get(0).getId()).getData();
        if (abstractProject.getCommonType().equals(2)) {
            // 邀请
            List<Long> sectionIdList = sectionList.stream().map(BidSection::getId).collect(Collectors.toList());
            List<TenderInviteEnterprise> inviteEnterpriseAcceptList = tenderInviteEnterpriseClient.findInviteEnterpriseByAcceptSectionList(sectionIdList).getData();
            // 筛选出回执人
            List<Long> ids = inviteEnterpriseAcceptList.stream().map(item -> Long.valueOf(item.getReceiptId())).collect(Collectors.toList());
            List<User> users =  userClient.getByUserIdList(ids).getData();
            userList.addAll(users);

            for (User user : userList) {
                if (userMap.containsKey(user.getPhone())) {
                    continue;
                }
                userMap.put(user.getPhone(), user);
            }
        } else {
            // 公开
            List<Long> upSectionId = sectionList.stream().filter(item -> item.getSignUpFlag().equals(LogicEnum.YES.getCode())).map(BidSectionDTO::getId).collect(Collectors.toList());
            List<Long> buySectionId = sectionList.stream().filter(item -> item.getSignUpFlag().equals(LogicEnum.NO.getCode())).map(BidSectionDTO::getId).collect(Collectors.toList());
            List<Long> downSectionId = sectionList.stream().map(BidSectionDTO::getId).collect(Collectors.toList());

            // 查询需要报名标段的投标人
            if (!CollUtil.isEmpty(upSectionId)) {
                Message<List<SupplyBidSignup>> upSectionUserList = sectionClient.findSupplyBidSignupInfoBySectionIdList(upSectionId);
                Set<Long> upBidderId = upSectionUserList.getData().stream().map(SupplyBidSignup::getBidderId).collect(Collectors.toSet());
                userId.addAll(upBidderId);
            }

            // 查询购买过该标段文件的投标人
            if (!CollUtil.isEmpty(buySectionId)) {
                Message<List<BidBuyRecord>> buySectionUserList = bidFileInfoClient.findBuyRecordBySectionIdList(buySectionId);
                Set<Long> buyBidderId = buySectionUserList.getData().stream().map(BidBuyRecord::getBuyUserId).collect(Collectors.toSet());
                userId.addAll(buyBidderId);
            }

            // 查询下载过该标段文件的投标人
            if (!CollUtil.isEmpty(downSectionId)) {
                Message<List<BidDownRecord>> downRecordUserList = sectionClient.findBidDownRecordBySectionIdList(downSectionId);
                Set<Long> downBidderId = downRecordUserList.getData().stream().map(BidDownRecord::getBidderId).collect(Collectors.toSet());
                userId.addAll(downBidderId);
            }
            if (CollUtil.isEmpty(userId)) {
                logger.info("发送短信用户列表为空");
                return;
            }

            List<Long> userIdList = userId.stream().collect(Collectors.toList());
            userList = userClient.getByUserIdList(userIdList).getData();


            userList = userClient.finBidUserByUserList(userList).getData();

            for (User user : userList) {
                // 如果是邀请项目只发送给一级用户
                if (abstractProject.getCommonType().equals(2) && !user.getAccountLevel().equals(1)) {
                    continue;
                }

                if (userMap.containsKey(user.getPhone())) {
                    continue;
                }
                userMap.put(user.getPhone(), user);
            }
        }

        if (CollUtil.isEmpty(userList)) {
            logger.info("发送短信用户列表为空");
            return;
        }

        for (String phone : userMap.keySet()) {
            JSONObject pushData = JSONUtil.createObj().putOpt("name", abstractProject.getProjectName());
            boolean sendSms = smsService.sendSms(phone, code, pushData);
            // 发送日志
            SmsSendLogDTO smsSendLogDTO = new SmsSendLogDTO();
            smsSendLogDTO.setSendPhone(phone);
            smsSendLogDTO.setSendModul(SmsTypeEnum.NOTICE.getShowName());
            smsSendLogDTO.setSendTemplate(SmsTypeEnum.NOTICE.getTemplate());
            smsSendLogDTO.setSendStatus(sendSms ? 1 : 2);
            smsSendLogDTO.setCreateTime(LocalDateTime.now());
            smsSendLogClient.save(smsSendLogDTO);
        }
    }

    /**
     * 投标人报名短信提醒
     *
     * @param supplyBidSignup
     * @param code
     * @return void
     * @author yuezheng
     * @date 2022/4/18 11:15 AM
     */
    @Async("taskExecutor")
    public void saveSupplyBidSignupInfo(SupplyBidSignupDTO supplyBidSignup, String code) throws InterruptedException {
        BidSectionDTO bidSectionDTO = new BidSectionDTO();
        supplyBidSignup.to(bidSectionDTO);
        BidSection bidSection = sectionClient.info(bidSectionDTO).getData();
        AbstractProject project = projectClient.detailBySectionId(bidSection.getId()).getData();
        User user = userClient.getByUserId(project.getUserId()).getData();
        String phone = user.getPhone();
        String signEndTime = bidSection.getSignEndTime().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm"));
        JSONObject pushData = JSONUtil.createObj().putOpt("name", project.getProjectName()).putOpt("time", signEndTime);
        boolean sendSms = smsService.sendSms(phone, code, pushData);
        // 发送日志
        SmsSendLogDTO smsSendLogDTO = new SmsSendLogDTO();
        smsSendLogDTO.setSendName(user.getUsername());
        smsSendLogDTO.setSendPhone(user.getPhone());
        smsSendLogDTO.setSendModul(SmsTypeEnum.REGISTRATION.getShowName());
        smsSendLogDTO.setSendTemplate(SmsTypeEnum.REGISTRATION.getTemplate());
        smsSendLogDTO.setSendStatus(sendSms ? 1 : 2);
        smsSendLogDTO.setCreateTime(LocalDateTime.now());
        smsSendLogClient.save(smsSendLogDTO);
    }


    /**
     * 标书发售短信提醒
     *
     * @param fileId
     * @param code
     * @return void
     * @author yuezheng
     * @date 2022/4/19 4:12 PM
     */
    @Async("taskExecutor")
    public void deploy(Long fileId, String code) {
        List<User> userList = null;

        List<BidSection> sectionList = sectionClient.listByFileId(fileId).getData();
        if (CollUtil.isEmpty(sectionList)) {
            logger.info("标书关联列表为空");
            return;
        }
        AbstractProject abstractProject = projectClient.detailBySectionId(sectionList.get(0).getId()).getData();
        // 邀请招标
        if (abstractProject.getCommonType().equals(2)) {
            List<Long> sectionIdList = sectionList.stream().map(BidSection::getId).collect(Collectors.toList());
            List<TenderInviteEnterprise> inviteEnterpriseAcceptList = tenderInviteEnterpriseClient.findInviteEnterpriseByAcceptSectionList(sectionIdList).getData();
            List<String> orgIdList = inviteEnterpriseAcceptList.stream().map(TenderInviteEnterprise::getOrgId).collect(Collectors.toList());
            if (CollUtil.isEmpty(orgIdList)) {
                return;
            }
            userList = userClient.findUserByOrgList(orgIdList).getData();
        } else if (abstractProject.getSignUpFlag().equals(LogicEnum.YES.getCode())) {
            // 查询需要报名标段的投标人
            if (!CollUtil.isEmpty(sectionList)) {
                List<Long> ids = sectionList.stream().map(BidSection::getId).collect(Collectors.toList());
                Message<List<SupplyBidSignup>> upSectionUserList = sectionClient.findSupplyBidSignupInfoBySectionIdList(ids);
                List<Long> upBidderId = upSectionUserList.getData().stream().map(SupplyBidSignup::getBidderId).collect(Collectors.toList());
                userList = userClient.getByUserIdList(upBidderId).getData();
            }
        }
        if (CollUtil.isEmpty(userList)) {
            logger.info("发送短线用户列表为空");
            return;
        }

        Set<String> phoneSet = userList.stream().map(User::getPhone).collect(Collectors.toSet());

        for (String phone : phoneSet) {
            JSONObject pushData = JSONUtil.createObj().putOpt("name", abstractProject.getProjectName());
            boolean sendSms = smsService.sendSms(phone, code, pushData);
            // 发送日志
            SmsSendLogDTO smsSendLogDTO = new SmsSendLogDTO();
            smsSendLogDTO.setSendPhone(phone);
            smsSendLogDTO.setSendModul(SmsTypeEnum.SALE.getShowName());
            smsSendLogDTO.setSendTemplate(SmsTypeEnum.SALE.getTemplate());
            smsSendLogDTO.setSendStatus(sendSms ? 1 : 2);
            smsSendLogDTO.setCreateTime(LocalDateTime.now());
            smsSendLogClient.save(smsSendLogDTO);
        }
    }

    /**
     * 投标人递交保证金短信提醒
     *
     * @param order
     * @param code
     * @return void
     * @author yuezheng
     * @date 2022/4/18 11:10 AM
     */
    @Async("taskExecutor")
    public void submitBond(UserOrderDTO order, String code) {
        if (!order.getFeeType().equals(1)) {
            logger.info("订单信息未支付");
            return;
        }

        AbstractProject project = projectClient.detailBySectionId(order.getSectionId()).getData();
        User user = userClient.getByUserId(project.getUserId()).getData();

        if (BeanUtil.isEmpty(user)) {
            logger.info("发送短信用户为空");
            return;
        }

        JSONObject pushData = JSONUtil.createObj().putOpt("name", project.getProjectName());
        boolean sendSms = smsService.sendSms(user.getPhone(), code, pushData);
        // 发送日志
        SmsSendLogDTO smsSendLogDTO = new SmsSendLogDTO();
        smsSendLogDTO.setSendPhone(user.getPhone());
        smsSendLogDTO.setSendModul(SmsTypeEnum.MARGIN.getShowName());
        smsSendLogDTO.setSendTemplate(SmsTypeEnum.MARGIN.getTemplate());
        smsSendLogDTO.setSendStatus(sendSms ? 1 : 2);
        smsSendLogDTO.setCreateTime(LocalDateTime.now());
        smsSendLogClient.save(smsSendLogDTO);
    }

    /**
     * 中标公示短息提醒
     *
     * @param bidCandidateDTO
     * @param code
     * @return void
     * @author yuezheng
     * @date 2022/4/18 11:20 AM
     */
    @Async("taskExecutor")
    public void publishCandidate(BidCandidateDTO bidCandidateDTO, String code) {
        List<User> userList = null;
        HashSet<Long> userId = new HashSet<>();
        Message<BidCandidateDTO> candidateDetail = dealClient.getCandidateDetail(bidCandidateDTO);
        if (candidateDetail.getData() == null) {
            logger.info("中标公示为空");
            return;
        }
        BidCandidateDTO bidCandidate = candidateDetail.getData();
        HashMap<String, User> userMap = new HashMap<>(16);

        //查询中标公示详情
        List<BidSection> sectionList = bidCandidate.getBidSectionList();
        if (CollUtil.isEmpty(sectionList)) {
            logger.info("关联标段为空");
            return;
        }

        AbstractProject abstractProject = projectClient.detailBySectionId(sectionList.get(0).getId()).getData();
        if (abstractProject.getCommonType().equals(2)) {
            List<Long> sectionIdList = sectionList.stream().map(BidSection::getId).collect(Collectors.toList());
            List<TenderInviteEnterprise> inviteEnterpriseAcceptList = tenderInviteEnterpriseClient.findInviteEnterpriseByAcceptSectionList(sectionIdList).getData();
            // 获取邀请人的id
            Set<String> receiptIdSet = inviteEnterpriseAcceptList.stream().map(TenderInviteEnterprise::getReceiptId).collect(Collectors.toSet());
            for (String receiptId : receiptIdSet) {
                userId.add(Long.valueOf(receiptId));
            }
        } else {
            // 公开招标
            List<Long> upSectionId = sectionList.stream().filter(item -> item.getSignUpFlag().equals(LogicEnum.YES.getCode())).map(BidSection::getId).collect(Collectors.toList());
            List<Long> buySectionId = sectionList.stream().filter(item -> item.getSignUpFlag().equals(LogicEnum.NO.getCode())).map(BidSection::getId).collect(Collectors.toList());
            List<Long> downSectionId = sectionList.stream().map(BidSection::getId).collect(Collectors.toList());

            // 查询需要报名标段的投标人
            if (!CollUtil.isEmpty(upSectionId)) {
                Message<List<SupplyBidSignup>> upSectionUserList = sectionClient.findSupplyBidSignupInfoBySectionIdList(upSectionId);
                Set<Long> upBidderId = upSectionUserList.getData().stream().map(SupplyBidSignup::getBidderId).collect(Collectors.toSet());
                userId.addAll(upBidderId);
            }

            // 查询购买过该标段文件的投标人
            if (!CollUtil.isEmpty(buySectionId)) {
                Message<List<BidBuyRecord>> buySectionUserList = bidFileInfoClient.findBuyRecordBySectionIdList(buySectionId);
                Set<Long> buyBidderId = buySectionUserList.getData().stream().map(BidBuyRecord::getBuyUserId).collect(Collectors.toSet());
                userId.addAll(buyBidderId);
            }

            // 查询下载过该标段文件的投标人
            if (!CollUtil.isEmpty(downSectionId)) {
                Message<List<BidDownRecord>> downRecordUserList = sectionClient.findBidDownRecordBySectionIdList(downSectionId);
                Set<Long> downBidderId = downRecordUserList.getData().stream().map(BidDownRecord::getBidderId).collect(Collectors.toSet());
                userId.addAll(downBidderId);
            }
        }

        if (!CollUtil.isEmpty(userId)) {
            List<Long> userIdList = userId.stream().collect(Collectors.toList());
            userList = userClient.getByUserIdList(userIdList).getData();
        }

        if (CollUtil.isEmpty(userList)) {
            logger.info("发送短信用户列表为空");
            return;
        }

        for (User user : userList) {
            if (userMap.containsKey(user.getPhone())) {
                continue;
            }
            userMap.put(user.getPhone(), user);
        }

        for (String phone : userMap.keySet()) {
            User user = userMap.get(phone);
            JSONObject pushData = JSONUtil.createObj().putOpt("name", abstractProject.getProjectName());
            boolean sendSms = smsService.sendSms(phone, code, pushData);
            // 发送日志
            SmsSendLogDTO smsSendLogDTO = new SmsSendLogDTO();
            smsSendLogDTO.setSendName(user.getUsername());
            smsSendLogDTO.setSendPhone(user.getPhone());
            smsSendLogDTO.setSendModul(SmsTypeEnum.PUBLICITY.getShowName());
            smsSendLogDTO.setSendTemplate(SmsTypeEnum.PUBLICITY.getTemplate());
            smsSendLogDTO.setSendStatus(sendSms ? 1 : 2);
            smsSendLogDTO.setCreateTime(LocalDateTime.now());
            smsSendLogClient.save(smsSendLogDTO);
        }
    }


    /**
     * 中标结果公示短信提醒
     *
     * @param bidWinResult
     * @param code
     * @return void
     * @author yuezheng
     * @date 2022/4/18 11:23 AM
     */
    @Async("taskExecutor")
    public void releaseBidWinResult(BidWinResultDTO bidWinResult, String code) {
        List<User> userList = null;
        HashSet<Long> userId = new HashSet<>();
        Message<BidWinResultDTO> bidWinResultDTOMessage = bidWinResultClient.bidWinResultInfoDetail(bidWinResult);
        HashMap<String, User> userMap = new HashMap<>(16);

        if (bidWinResultDTOMessage.getData() == null) {
            logger.info("中标结果为空");
            return;
        }
        List<BidSection> sectionList = bidWinResultDTOMessage.getData().getBidSectionList();
        if (CollUtil.isEmpty(sectionList)) {
            logger.info("关联标段为空");
            return;
        }
        AbstractProject abstractProject = projectClient.detailBySectionId(sectionList.get(0).getId()).getData();

        if (abstractProject.getCommonType().equals(2)) {
            List<Long> sectionIdList = sectionList.stream().map(BidSection::getId).collect(Collectors.toList());
            List<TenderInviteEnterprise> inviteEnterpriseAcceptList = tenderInviteEnterpriseClient.findInviteEnterpriseByAcceptSectionList(sectionIdList).getData();
            // 获取邀请人的id
            Set<String> receiptIdSet = inviteEnterpriseAcceptList.stream().map(TenderInviteEnterprise::getReceiptId).collect(Collectors.toSet());
            for (String receiptId : receiptIdSet) {
                userId.add(Long.valueOf(receiptId));
            }
        } else {
            List<Long> upSectionId = sectionList.stream().filter(item -> item.getSignUpFlag().equals(LogicEnum.YES.getCode())).map(BidSection::getId).collect(Collectors.toList());
            List<Long> buySectionId = sectionList.stream().filter(item -> item.getSignUpFlag().equals(LogicEnum.NO.getCode())).map(BidSection::getId).collect(Collectors.toList());
            List<Long> downSectionId = sectionList.stream().map(BidSection::getId).collect(Collectors.toList());

            // 查询需要报名标段的投标人
            if (!CollUtil.isEmpty(upSectionId)) {
                Message<List<SupplyBidSignup>> upSectionUserList = sectionClient.findSupplyBidSignupInfoBySectionIdList(upSectionId);
                Set<Long> upBidderId = upSectionUserList.getData().stream().map(SupplyBidSignup::getBidderId).collect(Collectors.toSet());
                userId.addAll(upBidderId);
            }

            // 查询购买过该标段文件的投标人
            if (!CollUtil.isEmpty(buySectionId)) {
                Message<List<BidBuyRecord>> buySectionUserList = bidFileInfoClient.findBuyRecordBySectionIdList(buySectionId);
                Set<Long> buyBidderId = buySectionUserList.getData().stream().map(BidBuyRecord::getBuyUserId).collect(Collectors.toSet());
                userId.addAll(buyBidderId);
            }

            // 查询下载过该标段文件的投标人
            if (!CollUtil.isEmpty(downSectionId)) {
                Message<List<BidDownRecord>> downRecordUserList = sectionClient.findBidDownRecordBySectionIdList(downSectionId);
                Set<Long> downBidderId = downRecordUserList.getData().stream().map(BidDownRecord::getBidderId).collect(Collectors.toSet());
                userId.addAll(downBidderId);
            }
        }

        if (!CollUtil.isEmpty(userId)) {
            List<Long> userIdList = userId.stream().collect(Collectors.toList());
            userList = userClient.getByUserIdList(userIdList).getData();
        }

        if (CollUtil.isEmpty(userList)) {
            logger.info("发送短信用户列表为空");
            return;
        }

        for (User user : userList) {
            if (userMap.containsKey(user.getPhone())) {
                continue;
            }
            userMap.put(user.getPhone(), user);
        }

        for (String phone : userMap.keySet()) {
            User user = userMap.get(phone);
            JSONObject pushData = JSONUtil.createObj().putOpt("name", abstractProject.getProjectName());
            boolean sendSms = smsService.sendSms(user.getPhone(), code, pushData);
            // 发送日志
            SmsSendLogDTO smsSendLogDTO = new SmsSendLogDTO();
            smsSendLogDTO.setSendName(user.getUsername());
            smsSendLogDTO.setSendPhone(user.getPhone());
            smsSendLogDTO.setSendModul(SmsTypeEnum.RESULT.getShowName());
            smsSendLogDTO.setSendTemplate(SmsTypeEnum.RESULT.getTemplate());
            smsSendLogDTO.setSendStatus(sendSms ? 1 : 2);
            smsSendLogDTO.setCreateTime(LocalDateTime.now());
            smsSendLogClient.save(smsSendLogDTO);
        }
    }

    /**
     * 质疑提醒短信提醒
     *
     * @param problem
     * @param code
     * @return void
     * @author yuezheng
     * @date 2022/4/18 11:10 AM
     */
    @Async("taskExecutor")
    public void sendOutProblem(ProblemDTO problem, String code) {
        Problem pro = clarifyClient.getProblem(problem.getId()).getData();
        AbstractProject project = projectClient.detailBySectionId(pro.getSectionId()).getData();
        User user = userClient.getByUserId(project.getUserId()).getData();
        String phone = user.getPhone();
        JSONObject pushData = JSONUtil.createObj().putOpt("name", project.getProjectName());
        boolean sendSms = smsService.sendSms(phone, code, pushData);
        // 发送日志
        SmsSendLogDTO smsSendLogDTO = new SmsSendLogDTO();
        smsSendLogDTO.setSendName(user.getUsername());
        smsSendLogDTO.setSendPhone(user.getPhone());
        smsSendLogDTO.setSendModul(SmsTypeEnum.QUESTION.getShowName());
        smsSendLogDTO.setSendTemplate(SmsTypeEnum.QUESTION.getTemplate());
        smsSendLogDTO.setSendStatus(sendSms ? 1 : 2);
        smsSendLogDTO.setCreateTime(LocalDateTime.now());
        smsSendLogClient.save(smsSendLogDTO);
    }

    /**
     * 审核通过短信提醒
     *
     * @param supplyBidSignup
     * @param code
     * @return void
     * @author yuezheng
     * @date 2022/4/18 9:06 AM
     */
    @Async("taskExecutor")
    public void passExamine(SupplyBidSignup supplyBidSignup, String code) throws InterruptedException {
        SupplyBidSignupDTO supplyBidSignupDTO = sectionClient.getSupplySignupInfo(supplyBidSignup).getData();
        Message<AbstractProject> abstractProjectMessage = projectClient.detailBySectionId(supplyBidSignupDTO.getSectionId());
        String projectName = abstractProjectMessage.getData().getProjectName();
        User user = userClient.getByUserId(supplyBidSignupDTO.getBidderId()).getData();
        String phone = user.getPhone();
        JSONObject pushData = JSONUtil.createObj().putOpt("name", projectName);
        boolean sendSms = smsService.sendSms(phone, code, pushData);
        // 发送日志
        SmsSendLogDTO smsSendLogDTO = new SmsSendLogDTO();
        smsSendLogDTO.setSendName(user.getUsername());
        smsSendLogDTO.setSendPhone(user.getPhone());
        smsSendLogDTO.setSendModul(SmsTypeEnum.APPROVED.getShowName());
        smsSendLogDTO.setSendTemplate(SmsTypeEnum.APPROVED.getTemplate());
        smsSendLogDTO.setSendStatus(sendSms ? 1 : 2);
        smsSendLogDTO.setCreateTime(LocalDateTime.now());
        smsSendLogClient.save(smsSendLogDTO);
    }

    /**
     * 审核不通过短信提醒
     *
     * @param supplyBidSignup
     * @param code
     * @return void
     * @author yuezheng
     * @date 2022/4/18 9:11 AM
     */
    @Async("taskExecutor")
    public void failExamine(SupplyBidSignup supplyBidSignup, String code) {
        SupplyBidSignupDTO supplyBidSignupDTO = sectionClient.getSupplySignupInfo(supplyBidSignup).getData();
        Message<AbstractProject> abstractProjectMessage = projectClient.detailBySectionId(supplyBidSignupDTO.getSectionId());
        String projectName = abstractProjectMessage.getData().getProjectName();
        User user = userClient.getByUserId(supplyBidSignupDTO.getBidderId()).getData();
        String phone = user.getPhone();
        JSONObject pushData = JSONUtil.createObj().putOpt("name", projectName);
        boolean sendSms = smsService.sendSms(phone, code, pushData);
        // 发送日志
        SmsSendLogDTO smsSendLogDTO = new SmsSendLogDTO();
        smsSendLogDTO.setSendName(user.getUsername());
        smsSendLogDTO.setSendPhone(user.getPhone());
        smsSendLogDTO.setSendModul(SmsTypeEnum.NOTAPPROVED.getShowName());
        smsSendLogDTO.setSendTemplate(SmsTypeEnum.NOTAPPROVED.getTemplate());
        smsSendLogDTO.setSendStatus(sendSms ? 1 : 2);
        smsSendLogDTO.setCreateTime(LocalDateTime.now());
        smsSendLogClient.save(smsSendLogDTO);
    }

    /**
     * 报价提醒短信提醒
     *
     * @param tradeSecondQuotationBidInfo
     * @param code
     * @return void
     * @author yuezheng
     * @date 2022/4/18 1:21 PM
     */
    @Async("taskExecutor")
    public void saveSecQuoBidInfo(TradeSecondQuotationBidInfoDto tradeSecondQuotationBidInfo, String code) {
        List<BidSectionOfferDTO> bidSectionOfferList = tradeSecondQuotationBidInfo.getBidSectionOfferList();

        Message<AbstractProject> abstractProjectMessage = projectClient.detailBySectionId(tradeSecondQuotationBidInfo.getSectionId());
        String projectName = abstractProjectMessage.getData().getProjectName();

        String turnsName = "一";
        // 获取当前轮次
        Message<List<TradeSecondQuotationBidInfoDto>> tradeSecondQuotationBidInfoDto1 = sectionClient.pollSecQuoBidInfo(tradeSecondQuotationBidInfo);
        if (tradeSecondQuotationBidInfoDto1.isSuccess() && null != tradeSecondQuotationBidInfoDto1.getData()) {
            turnsName = tradeSecondQuotationBidInfoDto1.getData().get(0).getTurnsName();
        }

        if (!CollUtil.isEmpty(bidSectionOfferList)) {
            for (BidSectionOfferDTO bidSectionOfferDTO : bidSectionOfferList) {
                // 投标人id
                Long offerId = bidSectionOfferDTO.getOfferId();
                Message<User> byUserId = userClient.getByUserId(offerId);
                if (byUserId.isSuccess() && null != byUserId.getData()) {
                    User user = byUserId.getData();

                    JSONObject pushData = JSONUtil.createObj().putOpt("name", projectName).putOpt("num", turnsName);
                    boolean sendSms = smsService.sendSms(user.getPhone(), code, pushData);
                    // 发送日志
                    SmsSendLogDTO smsSendLogDTO = new SmsSendLogDTO();
                    smsSendLogDTO.setSendName(user.getUsername());
                    smsSendLogDTO.setSendPhone(user.getPhone());
                    smsSendLogDTO.setSendModul(SmsTypeEnum.QUOTE.getShowName());
                    smsSendLogDTO.setSendTemplate(SmsTypeEnum.QUOTE.getTemplate());
                    smsSendLogDTO.setSendStatus(sendSms ? 1 : 2);
                    smsSendLogDTO.setCreateTime(LocalDateTime.now());
                    smsSendLogClient.save(smsSendLogDTO);
                }
            }
        }
    }
}
